/*
 * @Author: mjxjn@vip.qq.com
 * @Date: 2024-03-11 22:14:59
 * @LastEditors: mjxjn mjxjn@vip.qq.com
 * @LastEditTime: 2024-03-11 22:26:47
 * @FilePath: /Demo/assets/Runtime/EventManager.ts
 * @ApiFoxID: 
 * @Description: 
 */
import Singleton from "../Base/Singleton";

interface Iitem {
    callback: Function;
    ctx: unknown;
}

export default class EvenetManager extends Singleton {
    static get Instance () {
        return super.GetInstance<EvenetManager>();
    }

    private eventDic : Map<string, Array<Iitem>> = new Map()

    on(eventName: string, callback: Function, ctx?: unknown) {
        if(this.eventDic.has(eventName)) {
            this.eventDic.get(eventName).push({
                callback,
                ctx
            });
        } else {
            this.eventDic.set(eventName, [{
                callback,
                ctx
            }]);
        }
    }

    off(eventName: string, callback: Function) {
        if(this.eventDic.has(eventName)) {
            const index = this.eventDic.get(eventName).findIndex((item) => {
                return item.callback === callback;
            });
            index > -1 && this.eventDic.get(eventName).splice(index, 1);
        }
    }

    emit(eventName: string, ...args: any[]) {
        if(this.eventDic.has(eventName)) {
            this.eventDic.get(eventName).forEach(({callback, ctx}) => {
                ctx?callback.apply(ctx, args):callback(...args);
            })
        }
    }

    clear() {
        this.eventDic.clear();
    }
}